package gui.del_object;

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;

import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;

import objects.Departement;
import objects.Quartier;
import objects.Ville;

import bdd_handler.DepartementDAO;
import bdd_handler.QuartierDAO;
import bdd_handler.VilleDAO;
import bdd_handler.bdd;

public class Del_Departement extends JFrame implements ActionListener{

	private static final long serialVersionUID = 1L;

	private JFrame parent;

	private Departement d;

	private DepartementDAO dDAO;
	private VilleDAO vDAO;
	private QuartierDAO qDAO;

	private JButton valider, annuler;

	public Del_Departement(JFrame parent, Departement departement)
	{
		//recuperation de la fenetre parente
		this.parent=parent;
		this.parent.setVisible(false);

		//construction de la fenetre
		this.d=departement;
		this.setTitle("Suppression de : "+d.getNom());
		this.setSize(1020,650);
		this.setResizable(false);
		JPanel pan=new JPanel();
		pan.setLayout(null);
		this.setContentPane(pan);

		//creation des DAOs
		bdd db=new bdd();
		dDAO=new DepartementDAO(db.getConnection());
		vDAO=new VilleDAO(db.getConnection());
		qDAO=new QuartierDAO(db.getConnection());


		//creation objets internes
		JLabel avert=new JLabel("Attention! En supprimant le département '"+d.getNom()+"', vous allez aussi supprimer toutes les villes et quartiers à l'interieur. Cette action est irréversible.");
		valider=new JButton("supprimer");
		valider.addActionListener(this);
		annuler=new JButton("annuler");
		annuler.addActionListener(this);

		//placer les objets
		pan.add(avert);
		avert.setBounds(10,10,900,20);
		pan.add(annuler);
		annuler.setBounds(10, 40, 110, 20);
		pan.add(valider);
		valider.setBounds(130, 40, 110, 20);

		//action fermeture fenetre
		this.setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE);
		this.addWindowListener(
				new WindowAdapter(){
					public void windowClosing(WindowEvent e){
						close();

					}
				}
				);
		//afficher la fenetre
		this.setVisible(true);
	}

	private void close(){
		this.parent.setVisible(true);
		this.dispose();
	}

	public void actionPerformed(ActionEvent e) {

		Object source=e.getSource();

		if(source==valider)
		{

			Ville[] list_villes = vDAO.findbyDepartement(d.getId_departement());
			for(int k=0; k<list_villes.length;k++)
			{
				Quartier[] list_quartiers = qDAO.findByVille(list_villes[k].getId_ville());
				for(int l=0;l<list_quartiers.length;l++)
				{
					qDAO.delete(list_quartiers[l]);
				}
				vDAO.delete(list_villes[k]);
			}
			dDAO.delete(d);
			close();
		}
		if(source==annuler)
		{
			close();
		}
	}
}
